stddef.h
stddef.h
provides definitions of common types and macros, but does not declare any functions.
The types defined in this header file are as follows.
- ptrdiff_t: the type of data returned as the result of a pointer subtraction operation.
- size_t: the type returned by the
sizeof
operator. - wchar_t: a type large enough to hold a variety of characters.
All three of the above types are integer types, where ptrdiff_t
is a signed integer and size_t
is an unsigned integer.
stddef.h
defines two macros.
- NULL: null pointer.
- offsetof()
offsetof()
offsetof()
is a macro defined by stddef.h
to return the starting position of an attribute inside a Struct structure. Since the system may insert empty bytes between attributes of a Struct structure for byte alignment purposes, this macro is useful for determining the memory location of an attribute.
It is a parameterised macro that takes two arguments. The first argument is the Struct structure and the second argument is an attribute of that structure, returning the number of bytes between the Struct start position and that attribute.
struct s {
char a;
int b[2];
float c;
};
printf("%zu\n", offsetof(struct s, a)); // 0
printf("%zu\n", offsetof(struct s, b)); // 4
printf("%zu\n", offsetof(struct s, c)); // 12
For the Struct structure above, offsetof(struct s, a)
must equal 0
, because the a
attribute is the first attribute and has the same address as the Struct structure itself.
The system allocates 3 empty bytes after the a
attribute for byte alignment purposes, resulting in the b
attribute being stored in the 4th byte, so offsetof(struct s, b)
and offsetof(struct s, c)
are 4 and 12 respectively.